package com.sparrow.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Xml {

	public static void main(String[] args) throws Exception {
		String pengfuEncodeXML = xmlEncode("<div.*class=\"tex1\".*>([\\s\\S]*?)<\\/div>[\\s\\S]*<div class=\"new_1\">");
		// String
		// juhuaEncodeXML=xmlEncode("<div\\sclass=\"body\">([\\s\\S]*?)<\\/div><div class=\"share\">");
		// System.out.println(juhuaEncodeXML);
		System.out.println(pengfuEncodeXML);
	}

	public static Document getXmlDocumentByPath(String xmlFullPath,
			String dtdName) throws ParserConfigurationException, SAXException,
			IOException {
		final String finalDtdFile = dtdName;
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		if (!StringUtil.isNullOrEmpty(dtdName)) {
			docBuilder.setEntityResolver(new EntityResolver() {
				public InputSource resolveEntity(String publicId,
						String systemId) throws SAXException, IOException {
					InputSource is = new InputSource();
					is.setByteStream(this.getClass().getResourceAsStream(
							"/com/sparrow/core/" + finalDtdFile));
					is.setPublicId(publicId);
					is.setSystemId(systemId);
					return is;
				}
			});
		}
		Document doc = docBuilder.parse(new File(xmlFullPath));
		return doc;
	}

	/**
	 * 获取element文本
	 * 
	 * @author zhanglizhi
	 * @date Jul 9, 2011
	 * @version 1.0
	 * @param doc
	 * @param xmlKey
	 *            xml路径不包含根节点
	 * @return
	 */
	public static String getElementTextContent(Document doc, String xmlKey) {
		try {
			Element element = doc.getDocumentElement();
			String[] elementName = xmlKey.split("\\.");
			for (int i = 0; i < elementName.length; i++) {
				element = (Element) (element
						.getElementsByTagName(elementName[i])).item(0);
			}
			return element.getTextContent().trim();
		} catch (Exception ex) {
			return null;
		}
	}

	public static Element getElementByTagAttribute(Document doc,
			String tagName, String attributeName, String attributeValue) {
		Element element = doc.getDocumentElement();
		NodeList nodeList = element.getElementsByTagName(tagName);
		for (int i = 0; i < nodeList.getLength(); i++) {
			if (nodeList.item(i).getNodeType() == 1) {
				element = (Element) nodeList.item(i);
				if (element.getAttribute(attributeName).equals(attributeValue)) {
					return element;
				}
			}
		}
		return null;
	}

	public static Map<String, String> getInfo(String xml)
			throws ParserConfigurationException, SAXException, IOException {
		Map<String, String> info = new TreeMap<String, String>();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document documnet = builder.parse(new ByteArrayInputStream(xml
				.getBytes("UTF-8")));
		Element root = documnet.getDocumentElement();
		NodeList nl = root.getChildNodes();
		int length = nl.getLength();
		Node node = null;
		for (int i = 0; i < length; i++) {
			node = nl.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				info.put(node.getNodeName(), node.getTextContent());
			}
		}
		return info;
	}

	/**
	 * xml编码
	 * 
	 * &lt;<小于号
	 * 
	 * &gt;>大于号
	 * 
	 * &amp;&与（和）号
	 * 
	 * &apos;'单引号
	 * 
	 * &quot; " 双引号
	 * 
	 * @author zhanglizhi
	 * @date 2013-1-13
	 * @version 1.0
	 */
	public static String xmlEncode(String xml) {
		xml = xml.replace("&", "&amp;");
		xml = xml.replace("<", "&lt;");
		xml = xml.replace(">", "&gt;");
		xml = xml.replace("'", "&apos;");
		xml = xml.replace("\"", "&quot;");
		return xml;
	}

	/**
	 * xml解码
	 * 
	 * @author zhanglizhi
	 * @date 2013-1-13
	 * @version 1.0
	 * @param xml
	 * @return
	 */
	public static String xmlDecode(String xml) {
		xml = xml.replace("&lt;", "<");
		xml = xml.replace("&gt;", ">");
		xml = xml.replace("&amp;", "&");
		xml = xml.replace("&apos;", "'");
		xml = xml.replace("&quot;", "\"");
		return xml;
	}
}
